from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from models import Vhost
from settings import NGINX_PREFIX
from process.models import run_process
import os, sys

def index(request):
	fsv = os.listdir(NGINX_PREFIX + 'vhosts')
	fse = os.listdir(NGINX_PREFIX + 'enabled')
	return render(request, "vhost/index.html", { "vhosts":fsv, "enabled":fse })

def toggle(request):
	if request.GET.get('site'):
		s = request.GET.get('site')
		e = NGINX_PREFIX + 'enabled/' + s
		if os.path.exists(e):
			run_process(["unlink",e])
		else:
			os.chdir(NGINX_PREFIX + 'enabled/')
			run_process(["ln","-s","../vhosts/" + s])
	return redirect("/vhost/")

def add(request):
	return render(request, "vhost/add.html", { })

def save(request):
	n = Vhost()
	n.servername = "ducky-pond.com"
	n.port = "80"
	n.root_block.append("location / {")
	n.root_block.append("	root   /var/www;")
	n.root_block.append("	index  index.html;")
	n.root_block.append("}")

	str = render_to_string("vhost/save.html", { "vhost":n })
	f = open('/var/www/djanitor/.nginx/vhosts/' + n.servername, 'w')
	f.write(str)
	f.close()
	return str
